package cn.powertime.evaluation.idempotent;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author ZYW
 * @version 1.0
 * @date 2019-08-19 21:40
 */
@Service
public class TokenServiceImpl implements TokenService {

    private static final String REDIS_PREFIX = "token:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String createToken() {
        String uuid = IdWorker.get32UUID();
        String token = REDIS_PREFIX + uuid;
        redisTemplate.boundValueOps(token).set(token,30, TimeUnit.MINUTES);
        return token;
    }

    @Override
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(HEADER_TOKEN_NAME);
        if(StringUtils.isBlank(token)) {
            token = request.getParameter(HEADER_TOKEN_NAME);
            if(StringUtils.isBlank(token)) {
                throw new IdempotentException("幂等性认证Token为空");
            }
        }
        if(Optional.ofNullable(redisTemplate.hasKey(token)).orElse(false)) {
            throw new IdempotentException("请勿重复操作");
        }

        boolean delete = Optional.ofNullable(redisTemplate.delete(token)).orElse(false);
        if(!delete) {
            throw new IdempotentException("请勿重复操作");
        }
    }
}
